<?php

/**
 * 台湾CMS系统 twCMS
 *
 * (c) cighsen02 <xiayu@959602.com>
 *
 * Create at：2024.10.13
 * Update at: 2025.05.04
*/

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Services\User\Auth as AuthService;
use App\Services\User\ValidatorUser;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Validation\ValidationException;

class PasswordController extends Controller
{
    /**
     * 修改窗体
     *
     * @param  string  $accountType
     * @return  View
     */
    public function changePassword(string $accountType): View
    {
        return view('auth.change_password', ['title' => '密码修改', 'accountType' => $accountType]);
    }

    /**
     * 修改密码
     *
     * @param Request $request
     * @param ValidatorUser $validator
     * @param AuthService $auth
     * @param string $accountType
     * @return RedirectResponse
     */
    public function update(Request $request, ValidatorUser $validator, AuthService $auth, string $accountType): RedirectResponse
    {
        try {
            // 验证请求数据
            $validated = $validator->changePassword($request->all());
        }
        catch (ValidationException $e) {

            return back()->withErrors($e->errors())->withInput();
        }

        // 检查当前密码是否正确
        if (!$auth->checkCurrentPassword($validated['current_password'])) {
            return back()->withErrors(['current_password' => '当前密码不正确。']);
        }

        // 更新密码
        $auth->changePassword($validated);

        return back()->with('status', '密码已成功修改。');
    }
}
